package com.zy.stock.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.zy.stock.domain.Account;
import com.zy.stock.domain.Pager;
import com.zy.stock.domain.Stock;
import com.zy.stock.domain.StockTranscation;
import com.zy.stock.domain.User;
import com.zy.stock.domain.UserStockRl;
import com.zy.stock.dto.StockDto;
import com.zy.stock.dto.UserStockRlProfitDto;
import com.zy.stock.mapper.StockTranscationMapper;
import com.zy.stock.mapper.UserStockRlMapper;
import com.zy.stock.service.AccountService;
import com.zy.stock.service.UserService;
import com.zy.stock.service.UserStockRlService;
import com.zy.stock.util.CommonUtils;

@Transactional
@Component
public class AccountServiceImp implements AccountService{
	
	@Autowired
	private UserStockRlMapper userStockRlMapper;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserStockRlService userStockRlService;
	
	@Autowired
	private StockTranscationMapper stockTranscationMapper;
	
	@Override
	public List<Account> listAll() {
		// TODO Auto-generated method stub
		return null;
	}

	public Account findByUserId(Integer userId, String year) throws Exception {
	    // TODO Auto-generated method stub
	  User user = userService.findById(userId);
	  return buildAccount(user,year);
	}
	
	private Account buildAccount(User user,String year) throws Exception{
		Account obj = new Account();
		obj.setUserId(user.getId());
		obj.setUserName(user.getName());
		
		double profit = 0;
		double floatRrofit = 0;
		double value = 0;
		double incomeCash = 0;
		double payCash = 0;
		
		//遍历仓的列表
		List<UserStockRlProfitDto> profitDtos = stockTranscationMapper.findProfit(user.getId(),year);
		for(UserStockRlProfitDto profitDto:profitDtos){
			//盈亏
			profit +=profitDto.getProfit();
			//还有剩余 计算浮动盈亏
			if(profitDto.getRestNum()>1){
				UserStockRl rl = userStockRlService.findById(profitDto.getUserStockRlId());
				double temp = userStockRlService.calculateEarnings(rl);
				profitDto.setFloatProfit(temp);
				floatRrofit+=temp;
			}
			//市值
			value+=profitDto.getValue();
			//现金
			incomeCash+=profitDto.getIncomeCash();
			//支出
			payCash+=profitDto.getPayCash();
		}
		//总资产
//		double totalValue = user.getPrincipal()-payCash+value+incomeCash;
		double totalValue = user.getCash()+value;
		
		//精度处理
		BigDecimal profitBD = new BigDecimal(profit);
		profitBD = profitBD.setScale(0, BigDecimal.ROUND_HALF_UP);
		obj.setProfit(profitBD);//盈亏
		
		BigDecimal floatProfitBD = new BigDecimal(floatRrofit);
		floatProfitBD = floatProfitBD.setScale(0, BigDecimal.ROUND_HALF_UP);
		obj.setFloatProfit(floatProfitBD);//浮动盈亏
		
		BigDecimal valueBD = new BigDecimal(value);
		valueBD = valueBD.setScale(0, BigDecimal.ROUND_HALF_UP);
		obj.setValue(valueBD);//市值
		
		BigDecimal cash = new BigDecimal(incomeCash);
		cash = cash.setScale(0, BigDecimal.ROUND_HALF_UP);
		obj.setCash(cash);//卖出金额
		
		BigDecimal principal = new BigDecimal(user.getPrincipal());
		obj.setBeginCash(principal);//本金
		
		int freeCashDouble = (int) (user.getPrincipal() - payCash + incomeCash);
		BigDecimal freeCash = null;
//		BigDecimal freeCash = new BigDecimal(freeCashDouble);
		if(user.getCash()!=null){
	       freeCash = new BigDecimal(user.getCash());
		}else{
		   freeCash = new BigDecimal(freeCashDouble);
		}
		freeCash.setScale(0, BigDecimal.ROUND_HALF_UP);
		obj.setFreeCash(freeCash);//可用现金 改为账户属性
		
		BigDecimal payCashBD = new BigDecimal(payCash);
		obj.setPayCash(payCashBD);
		
		BigDecimal totalValueBD = new BigDecimal(totalValue);
		totalValueBD = totalValueBD.setScale(0, BigDecimal.ROUND_HALF_UP);
		obj.setTotalValue(totalValueBD);//总资产
		
		//计算盈亏收益率 （改为除以总支出）
//		double earningRate = profit*100/user.getPrincipal();
		if(payCash>0){
		  double earningRate = profit*100/payCash;
	      BigDecimal earningRateBD = new BigDecimal(earningRate);
	      earningRateBD = earningRateBD.setScale(2, BigDecimal.ROUND_HALF_UP);
	      obj.setEarningRate(earningRateBD.toString()+"%");
		}else{
		  obj.setEarningRate("暂无");
		}
		
		
		//仓位
		double cangWei = value*100/totalValueBD.doubleValue();
		BigDecimal cangWeiBD = new BigDecimal(cangWei);
		cangWeiBD = cangWeiBD.setScale(2, BigDecimal.ROUND_HALF_UP);
		obj.setCangWei(cangWeiBD.toString()+"%");
		return obj;
	}

	@Override
	public Pager<List<Account>> findByCase(Pager<Account> pager)
			throws Exception {
		// TODO Auto-generated method stub
		Pager<List<Account>> result = new Pager<List<Account>>();
		try{
			Account obj = pager.getT();
			Integer begin = (pager.getPagenow() - 1) * pager.getSize();
			obj.setStart(begin);
			obj.setSize(pager.getSize());
			obj.setOrder(pager.getOrder());
			obj.setOrderCol(pager.getOrderCol());
			List<Account> list = new  ArrayList<Account>();
			if(StringUtils.isEmpty(obj.getUserName())){
				List<User> users = userService.findAll();
				for(User user:users){
					list.add(buildAccount(user,obj.getYear()));
				}
				Integer total = list.size();
				Integer totalpage = CommonUtils.getTotalPage(pager, total);
				result.setTotal(total);
				result.setT(list);
				result.setTotalpage(totalpage);
			}else{
				User user = userService.findByName(obj.getUserName());
				list.add(buildAccount(user,obj.getYear()));
				result.setTotal(1);
				result.setT(list);
				result.setTotalpage(1);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception("BillServiceImp.class findByCase function error : " + e.toString());
		}
		return result;
	}

  
	
}
